import React,{Component} from "react"
import axios from 'axios'
import {Link} from "react-router-dom";
import {getCourseList,getRankDetail,updataRank,deletecourse} from "../../api/course"
import $ from "jquery"
import './index.css'
import deleteImg from "../../images/delete.png"
import addImg from "../../images/add.png"
import backImg from "../../images/back.png"
import loadingImg from "../../images/loading.gif"
// import AppDB from 'https://game.jixiucloud.cn/lib/jxconsoledb.min.js?id=17'
import AppDB from "../../api/appdb.js";
class Index extends Component{
    constructor(props){
        super(props);
        this.state = {
           coursedata:{
            coursetitle:'',
            courseDescription:'',
            courseid:'',
            coursetutor:'',
            imgurl:'',
            addItemList:[
                {id:1,title:'',videotitle:'视频标题' ,linktitle:'视频地址',link:''}
                ]
           },
           coursetitles:[],
           ranks:[],
           number:1,
           newslist:[],
           selectedIndex:'',
           deletebtn:true,
           oid:'',
           pageloading:false,
           courselink:false
          
        }
    }
    componentDidMount(){
        let that = this
        let login = localStorage.getItem('loginadmin') 
        if(!login){
           that.props.history.push(this.state.courselink?'./loginadmin':'/fanscourse/loginadmin')
           return
        }
        that.setState({pageloading:true})
        let isLoginCon = that.props.userinfo && that.props.userinfo.AccessToken
        // if(!isLoginCon){
        //    that.setState({isLoginCon:true})
        //    return
        // }
        that.getdata()
        if(that.props.match.params.id == 'add'){
            that.setState({submitbtn:true,deletebtn:false})
            if(that.props.location.state && that.props.location.state.postid){
                let data = this.state.coursedata;
                data.coursetitle = that.props.location.state.title;
                data.courseid = that.props.location.state.postid;
                    this.setState({courseid:data,coursetitle:data});
                        let news = that.state.coursedata
                    news.coursetutor = ""
                    news.imgurl = ""
                    news.courseDescription = ""
                    news.addItemList = [ {id:1,title:'',videotitle:'视频标题' ,linktitle:'视频地址',link:''}]
                        that.setState({
                            coursedata:news,
                            deletebtn:false
                        })
            }
         }else if(that.props.match.params.id == ''){
             that.props.history.push(this.state.courselink?'./rankadmin/add':'/fanscourse/rankadmin/add')
         }else{
             that.setState({detelebtn:true,savebtn:true})
             getRankDetail(that.props.match.params.id,'news').then(res=>{
                 let data= JSON.parse(res.data.data.data)[0] || JSON.parse(res.data.data.data)[0].data                
                 let news = that.state.coursedata
                 news.coursetitle = data.coursetitle
                 news.courseid =data.courseid
                 news.coursetutor = data.coursetutor
                 news.imgurl = data.imgurl
                 news.courseDescription = data.courseDescription
                 news.addItemList = data.addItemList
                     that.setState({
                         coursedata:news,
                         oid:data._id.$oid
                     })
             }).catch((err)=>{
                 that.setState({submitbtn:true,detelebtn:false,savebtn:false})
             })
               
          }
    }
    
    onInputchange(index,name,e){
        if(name == 'title'){
            let value = this.state.coursedata.addItemList;
            value[index].title = e.target.value;
            this.setState({value});
        }else if(name == 'link'){
            let value = this.state.coursedata.addItemList;
            value[index].link = e.target.value;
            this.setState({value});
        }else if(name == 'coursetutor'){
            let data = this.state.coursedata;
                data.coursetutor = e.target.value;
                this.setState({coursetutor:data});
        }else if(name == 'courseDescription'){
            let data = this.state.coursedata;
            data.courseDescription = e.target.value;
            this.setState({courseDescription:data});
        }
         console.log(this.state.coursedata)
        
    }
    addvideo(){
        this.setState({number:++this.state.number});
        let value = {id:this.state.number,title:'',videotitle:'视频标题' ,linktitle:'视频地址',link:''}
        this.state.coursedata.addItemList.push(value)
        this.setState({addItemList:this.state.coursedata.addItemList});
    }
    deleteItem(index){
        let newaddItemList = []
        if(this.state.coursedata.addItemList.length<=1){
            alert('至少需要添加一个视频')
            return
        }
        let data = this.state.coursedata
            this.state.coursedata.addItemList.splice(index,1)
            newaddItemList.push(this.state.coursedata.addItemList)
            console.log(newaddItemList)
            data.addItemList= this.state.coursedata.addItemList
        this.setState({
            addItemList:data
        })
       
    }
    getdata(){
        let that = this
        getCourseList(0,20).then((data)=>{
            // let title = that.state.coursedata
            // title.coursetitles = data.data
            that.setState({coursetitles:data.data,pageloading:false})
        })
    }
    handleChangetitle= (e,name) => {
        let that = this
        if(!e.target.selectedIndex){
            let data = this.state.coursedata;
            data.courseid = ''
            this.setState({courseid:data});
            return
        }
       
        let data = this.state.coursedata;
            data.coursetitle = this.state.coursetitles[e.target.selectedIndex-1].Title;
            data.courseid = this.state.coursetitles[e.target.selectedIndex-1].PostId;
        this.setState({courseid:data,coursetitle:data});
        getRankDetail('','news').then(res=>{
            that.setState({
                newslist:JSON.parse(res.data.data.data)
            })
            let item = that.state.newslist
            for(let i=0;i<item.length;i++){
                if(that.state.coursedata.courseid == item[i].courseid){
                    let news = that.state.coursedata
                    news.courseid = item[i].courseid
                    news.coursetutor = item[i].coursetutor
                    news.imgurl = item[i].imgurl
                    news.coursetutor = item[i].coursetutor
                    news.courseDescription = item[i].courseDescription
                    news.addItemList =  item[i].addItemList
                
                        that.setState({
                            coursedata:news,
                            oid:item[i]._id.$oid,
                            deletebtn:true
                        })
                        return
                  }else{
                    let news = that.state.coursedata
                    news.coursetutor = ""
                    news.imgurl = ""
                    news.courseDescription = ""
                    news.addItemList = [ {id:1,title:'',videotitle:'视频标题' ,linktitle:'视频地址',link:''}]
                        that.setState({
                            coursedata:news,
                            deletebtn:false
                        })
                       
                  }
            }
          
            console.log(that.state.newslist)
        })
    }
    load(ele){
        let that = this
        var form = new FormData();
        var file = ele.target.files[0];
        form.append('value', file);
        if(!file){return}
        var settings = {
            "url": `${window.AppOptions.Server}/api/file/UploadImage`,
            "method": "POST",
            "processData": false,
            "mimeType": "multipart/form-data",
            "contentType": false,
            "data": form
        };

        $.ajax(settings).done(function (response) {
            //that.postModel.avatar = JSON.parse(response).data;
            let data = that.state.coursedata
                data.imgurl = JSON.parse(response).data
            that.setState({imgurl:data.imgurl})
        });



        // this.refs.loading.style.display="block"
        // let file=this.refs.file
        // console.log(file.files[0])
        // let forData=new FormData
        // forData.append('headfile',file.files[0])
        // var url="http://vueshop.glbuys.com/api/user/myinfo/formdatahead?token=1ec949a15fb709370f"
        // axios({
        //      method:"post",
        //      url:url,
        //      data:forData
        // }).then(res=>{
        // this.refs.loading.style.display="none"
             
        //      console.log(res.data)
        //      if(res.data.code==200)
        //      {
        //           let temp="//vueshop.glbuys.com/userfiles/head/"
        //           this.setState({
        //                 imgurl:temp+res.data.data.msbox
        //           })
        //      }
        // })
    }
    save(){
        let that =this;
        // coursedata:{
        //     coursetitle:'',
        //     courseid:'',
        //     coursetutor:'',
        //     imgurl:'',
        let title = that.state.coursedata.coursetitle
        let id = that.state.coursedata.courseid
        let tutor = that.state.coursedata.coursetutor
        let imgurl = that.state.coursedata.imgurl
        let videos = that.state.coursedata.addItemList
       
        if(!title){
           alert('课程标题不能为空')
           return
        }else if(!id){
            alert('课程ID不能为空')
            return
        }else if(!tutor){
            alert('导师名称不能为空')
            return
        }else if(!imgurl){
            alert('头像不能为空')
            return
        }
        let video = videos.map(item=>{
            if(item.title =='' || item.link== ''){
                alert('视频标题和视频地址不能为空')
                return true
            }
        })
        for(let i =0;i<video.length;i++){
            if(video[i] == true){
                return
            }
        }
        let data= JSON.stringify(that.state.coursedata)
        updataRank(that.state.oid,data,'news').then(res=>{
            that.props.history.push('/fanscourse/courselist')
        })
       
        // window.AppDB.Post(
        //     'news',
        //     JSON.stringify(that.state.coursedata),
        // ).then(x => {
        //     that.props.history.push("/courselist")
        // });
    }
    back(){
        this.props.history.push('/fanscourse/courselist')
    }
    delete(){
        let that =this
        let id = that.state.oid || that.props.match.params.id 
        deletecourse(id).then(res=>{
            that.props.history.push(this.state.courselink?'/courselist':'/fanscourse/courselist')
        })
    }
	render(){
        let {courseid,coursetutor,addItemList,imgurl,courseDescription} = this.state.coursedata
		return(
           <div className="course">
               <div className='header'>
                   <div className='back' onClick={this.back.bind(this)}><img src={backImg}/></div>
                   <div className='title'>课程数据</div>
               </div>
              <div className='coursecon'>
                  <div className='label'>课程标题</div>
                  <div className='input'>
                  <select
                        // showSearch
                        // style={{ width: 200 }}
                        // 选择框默认文字
                        placeholder="全部"
                        // 选项变化时触发事件
                        // onChange={this.handleChange}
                        onChange={this.handleChangetitle}
                    >
                        <option value="">{this.state.coursedata.courseid?this.state.coursedata.coursetitle:'全部'}</option>
                        {/*将符合结构的数据循环进去*/}
                        {
                        this.state.coursetitles.map((item,index)=>{
                            return <option key={index} value={item.Title}>{item.Title}</option>
                        })
                      
                        }
                </select>
                      {/* <input type='text' value={coursetitle} onChange={this.onInputchange.bind(this,'','coursetitle')} placeholder='仅用于识别，以星伴后台为准'/> */}
                  </div>
              </div>
              <div className='coursecon'>
                  <div className='label'>课程系列ID</div>
                  <div className='input'>
                      <input type='text' readOnly='readonly' value={courseid} placeholder='对接星伴后台'/>
                  </div>
              </div>
              <div className='coursecon'>
                  <div className='label'>老师名称</div>
                  <div className='input'>
                      <input type='text' maxLength='14' value={coursetutor} onChange={this.onInputchange.bind(this,'','coursetutor')} placeholder='显示名称'/>
                  </div>
              </div>
              <div className='coursecon'>
                    <div className='label'>老师头像</div>
                    <div className="userImg">
                            {/* <div className="loading" ref="loading">上传中....</div> */}
                            
                            <input type="file" ref="file" id='uploadImage' onChange={this.load.bind(this)}/>
                            {imgurl?<img src={imgurl}/>:<div className='upload'></div>}
                    </div>
                 
              </div>
              {/* <div className='coursecon'>
                  <div className='label'>老师介绍</div>
                  <div className='input'>
                      <input type='text' value={courseDescription} onChange={this.onInputchange.bind(this,'','courseDescription')} placeholder='老师介绍'/>
                  </div>
              </div> */}
              <div className='videocon'>
                    {addItemList.map((item,index)=>
                    <div key={index} className='coursecontain'>
                      <div className='coursecon'>
                        <div className='label'>{item.videotitle}</div>
                        <div className='input'>
                            <input maxLength='14' value={item.title} onChange={this.onInputchange.bind(this,index,'title')}></input>
                        </div>
                      </div>
                      <div className='coursecon'>
                        <div className='label'>{item.linktitle}</div>
                        <div className='input'>
                            <input  value={item.link} onChange={this.onInputchange.bind(this,index,'link')}></input>
                        </div>
                      </div>
                          <span className='del' onClick={this.deleteItem.bind(this,index)}><img src={deleteImg}></img></span>
                            </div>)}
                      <div className='addvideo' onClick={this.addvideo.bind(this)}><img src={addImg}/></div>
                </div>
               <div className='save' onClick={this.save.bind(this)}>保存</div>
               {this.state.deletebtn?<div className='qx' onClick={this.delete.bind(this)}>删除</div>:''}
               <div className='qx' onClick={this.back.bind(this)}>取消</div>
               {this.state.pageloading?<div className='popuploading' >
                   <div className='loading'><img src={loadingImg}/></div>
               </div>:''}
           </div>
		)
	}
}
 

export default Index